//
//  RHLocalSettingCell.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/9.
//

#import "RHLocalSettingCell.h"
#import "ZYSwitch.h"
 NSString *const LocalSettingAddSubCell    = @"LocalSettingAddSubCell";
 NSString *const LocalSettingSelectCell    = @"LocalSettingSelectCell";
 NSString *const LocalSettingTextInputCell = @"LocalSettingTextInputCell";
 NSString *const LocalSettingSwitchCell    = @"LocalSettingSwitchCell";
 NSString *const LocalSettingCommandCell   = @"LocalSettingCommandCell";
 NSString *const LocalSettingDateCell      = @"LocalSettingDateCell";
@interface RHLocalSettingCell()<QMUITextFieldDelegate>
@property (nonatomic, strong) QMUILabel *titleLab;
//下拉选择项
@property (nonatomic, strong) QMUILabel *contentLab;

@property (nonatomic, strong) QMUILabel *unitLab;

//加减项,文本项
@property (nonatomic, strong) QMUITextField *textField;

@property (nonatomic, strong) QMUIButton *addBtn;

@property (nonatomic, strong) QMUIButton *reduceBtn;

@property (nonatomic, strong) QMUIButton *selectBtn;

@property (nonatomic, strong) ZYSwitch *swith;

@property (nonatomic, assign) BOOL isReadOnly;

@property (nonatomic, strong) UIImageView *arrowImg;
@end
@implementation RHLocalSettingCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    kWeakSelf;
    self.contentView.backgroundColor = CFTabViewBgColor;
    UIView *bgView = kView;
    [self.contentView addSubview:bgView];
    bgView.backgroundColor = UIColor.whiteColor;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    _titleLab = [[QMUILabel alloc]init];
    [bgView addSubview:_titleLab];
    _titleLab.numberOfLines = 0;
    _titleLab.font = [UIFont systemFontOfSize:13];
    _titleLab.textColor = kCOLOR_HEX(@"3F4443");
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    _unitLab = [[QMUILabel alloc]init];
    [bgView addSubview:_unitLab];
    _unitLab.numberOfLines = 2;
    _unitLab.adjustsFontSizeToFitWidth = YES;
    _unitLab.minimumScaleFactor = 0.6;
    _unitLab.font = [UIFont systemFontOfSize:12];
    _unitLab.textColor = kCOLOR_HEX(@"3F4443");
    [_unitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-10);
        make.centerY.mas_offset(0);
    }];
    
    //加减
    if([self.reuseIdentifier isEqualToString:LocalSettingAddSubCell]){
        [bgView addSubview:self.addBtn];
        [bgView addSubview:self.reduceBtn];
        [bgView addSubview:self.textField];

        self.textField.delegate = self;
        [_reduceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.unitLab.mas_left).offset(-10);
            make.width.height.offset(35);
            make.centerY.equalTo(weakSelf.contentView);
        }];
        [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.reduceBtn.mas_left).offset(-5);
            make.centerY.equalTo(weakSelf.reduceBtn);
            make.width.offset(kScaleW(80));
            make.height.equalTo(weakSelf.reduceBtn);
        }];
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.addBtn.mas_left).offset(-5);
        }];
        
        [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.textField.mas_left).offset(-5);
            make.centerY.equalTo(weakSelf.textField);
            make.width.height.equalTo(weakSelf.reduceBtn);
        }];
    }
    
    //文本输入
    if([self.reuseIdentifier isEqualToString:LocalSettingTextInputCell]){
        [bgView addSubview:self.textField];
//        self.textField.keyboardType = UIKeyboardTypeASCIICapable;
        self.textField.placeholder = @"请输入".rh_localized;
        [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-15);
            make.centerY.mas_offset(0);
            make.width.offset(kScaleW(150));
            make.height.offset(35);
        }];
        
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf.textField.mas_left).offset(-5);
        }];
        
        [[RACSignal merge:@[_textField.rac_textSignal,RACObserve(_textField, text)]]subscribeNext:^(NSString  *_Nullable text) {
            weakSelf.paraModel.content = text;
            
        }];
    }
    
    //选择列表
    if([self.reuseIdentifier isEqualToString:LocalSettingSelectCell]){
      
        UIView *selectView = kView;
        selectView.layer.borderColor = kCOLOR_HEX(@"DCDCDC").CGColor;
        selectView.layer.borderWidth = 1;
        selectView.layer.cornerRadius = 5;
        selectView.layer.masksToBounds = YES;
        [bgView addSubview:selectView];
        [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(5);
            make.bottom.mas_offset(-5);
            make.right.mas_offset(-15);
           
        }];
        
        _arrowImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_down"]];
        [selectView addSubview:_arrowImg];
        [_arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(15);
            make.right.mas_offset(-5);
            make.centerY.mas_offset(0);
        }];
        
        
        [selectView addSubview:self.contentLab];
        [self.contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(5);
            make.top.mas_offset(5);
            make.bottom.mas_offset(-5);
            make.height.greaterThanOrEqualTo(@(25));
            make.right.equalTo(weakSelf.arrowImg.mas_left).offset(-5);
            make.width.offset(120);
        }];
        
        
        [bgView addSubview:self.selectBtn];
        [_selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(selectView);
        }];
        
        
        
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(selectView.mas_left).offset(-10);
        }];
    }
    
    //开关
    if([self.reuseIdentifier isEqualToString:LocalSettingSwitchCell]){
        ZYSwitch *swith = [[ZYSwitch alloc]initWithFrame:CGRectMake(0, 0, 45, 25)];
        swith.onTintColor = CMainColorGreen;
        [bgView addSubview:swith];
        self.swith = swith;
        [swith mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-15);
            make.centerY.equalTo(weakSelf.titleLab);
            make.width.offset(45);
            make.height.offset(25);
        }];
        [[swith rac_signalForControlEvents:UIControlEventValueChanged]subscribeNext:^(__kindof UISwitch * _Nullable x) {
            weakSelf.paraModel.content = [NSString stringWithFormat:@"%@",@(x.isOn)];
            //如果是位数据,当前位的值改变了,要同步更新其他位的原始值
            if(weakSelf.paraModel.isBit){
                if(weakSelf.bitValueChangBlock){
                    weakSelf.bitValueChangBlock(weakSelf.paraModel);
                }
            }
        }];
    }
    
    //指令
    if([self.reuseIdentifier isEqualToString:LocalSettingCommandCell]){
        UIView *itemView = kView;;
        itemView.backgroundColor = CFTabViewBgColor;
        itemView.layer.cornerRadius = 8;
        itemView.layer.masksToBounds = YES;
        [bgView addSubview:itemView];
        [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.top.mas_offset(10);
            make.bottom.mas_offset(-5);
            make.height.offset(kScaleW(45));
        }];
        
        QMUIButton *sendBtn = [[QMUIButton alloc]init];
        [itemView addSubview:sendBtn];
        [sendBtn setTitle:@"发送".rh_localized forState:UIControlStateNormal];
        [sendBtn setTitleColor:kCOLOR_HEX(@"56C271") forState:UIControlStateNormal];
        sendBtn.titleLabel.font = kSYSTEMFONT(14);
        sendBtn.backgroundColor = [UIColor colorWithHexString:@"56C271" alpha:0.2];
        [sendBtn setCornerRadius:8];
        [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-10);
            make.top.mas_offset(10);
            make.bottom.mas_offset(-10);
            make.width.offset(kScaleW(60));
        }];
        
        [itemView addSubview:self.titleLab];
        [self.titleLab mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(10);
            make.centerY.mas_offset(0);
            make.right.equalTo(sendBtn.mas_left).offset(-5);
            
        }];
        [bgView bringSubviewToFront:self.titleLab];
        
        [[sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            if(weakSelf.commandBlock){
                weakSelf.commandBlock();
            }
        }];
        
    }
    //选择时间
    if([self.reuseIdentifier isEqualToString:LocalSettingDateCell]){
        [bgView addSubview:self.textField];
        _textField.userInteractionEnabled = NO;
        [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-15);
            make.centerY.mas_offset(0);
            make.width.offset(kScaleW(140));
            make.height.offset(kScaleW(30));
        }];
        [bgView addSubview:self.selectBtn];
        [_selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.textField);
        }];
        
    }
}

-(void)setParaModel:(RHLocalSettingModel *)paraModel
{
    _paraModel = paraModel;
    
    _textField.userInteractionEnabled = !paraModel.readOnly;
    _textField.textColor = paraModel.isReadOnly?kCOLOR_HEX_A(@"3F4443", 0.6):kCOLOR_HEX(@"3F4443");
    _arrowImg.hidden = paraModel.isReadOnly;
    self.unitLab.text = paraModel.unit.rh_localized;
    
    [self.unitLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(paraModel.unit.length>0?30:0);
    }];
  
    kWeakSelf;
    self.titleLab.text = paraModel.nickname.rh_localized;
    //加减
    if([self.reuseIdentifier isEqualToString:LocalSettingAddSubCell]){
        self.textField.text = paraModel.content;
        self.addBtn.enabled = [paraModel.content doubleValue] >= [self.paraModel.max doubleValue]?NO:YES;
        self.reduceBtn.enabled = [paraModel.content doubleValue] <= [self.paraModel.min doubleValue]?NO:YES;
    }
    
    //文本输入
    if([self.reuseIdentifier isEqualToString:LocalSettingTextInputCell]){
//        self.textField.maximumTextLength = paraModel.maxLength;
        self.textField.text = paraModel.content;
    
        CGFloat textLeng = [paraModel.content getStringWidthFont:self.textField.font limitHeight:25];
        //长度控制在60 到150之间
        CGFloat width = 150;
        if(textLeng+10 > width){
            width = 180;
        }
       
        [self.textField mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.offset(width);
        }];
    }
    
    //选择列表
    if([self.reuseIdentifier isEqualToString:LocalSettingSelectCell]){
        self.selectBtn.enabled = !self.paraModel.isReadOnly;
        _textField.hidden = YES;
        
//        NSLog(@"---->枚举值:%@",paraModel.content);
        [paraModel.selectList enumerateObjectsUsingBlock:^(RHLocalSettingOptionModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if((paraModel.content.length>0) && ([paraModel.content integerValue] == obj.textValue)){
                weakSelf.contentLab.text = obj.text.rh_localized;
                *stop = YES;
            }else{//没有匹配到
                weakSelf.contentLab.text = @"--";
                //解除安全锁定,  1:解除安全锁定   1以外的都是"其他值"
                if ([paraModel.field isEqualToString:@"Pck_RmvSafetyLock"]) {
                    if (paraModel.content.length>0 && [paraModel.content integerValue] != 1) {
                        weakSelf.contentLab.text = @"其他值".rh_localized;
                    }
                }
                
                if ([paraModel.field isEqualToString:@"Ems_InvAddr"]) {//逆变器显示NULL
                    weakSelf.contentLab.text = @"NULL";
                }
            }
            
 
        }];
        CGFloat textLeng = [self.contentLab.text getStringWidthFont:self.contentLab.font limitHeight:25];
        //长度控制在60 到150之间
        CGFloat width = 120;
        if(textLeng > width){
            width = 150;
        }
       
        [self.contentLab mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.offset(width);
        }];
        
        if(paraModel.content.length == 0){
            self.contentLab.text = nil;
        }
        
    }
    
    //开关
    if([self.reuseIdentifier isEqualToString:LocalSettingSwitchCell]){
        self.swith.on = [paraModel.content integerValue] == 1;
    }
    
    //指令
    if([self.reuseIdentifier isEqualToString:LocalSettingCommandCell]){
        self.titleLab.text = paraModel.nickname.rh_localized;
    }
    //时间
    if([self.reuseIdentifier isEqualToString:LocalSettingDateCell]){
        self.textField.text = paraModel.content;
    }
    
    _addBtn.enabled = !paraModel.readOnly;
    _reduceBtn.enabled = !paraModel.readOnly;
}

#pragma mark ------- action -----------
//加
-(void)addAction
{
    if([self.paraModel.format isEqualToString:@"int"]){
        NSInteger curValue = [self.paraModel.content integerValue];
        NSInteger step = [self.paraModel.unitLen integerValue];
        if(curValue< [self.paraModel.max integerValue]){
            curValue += step;
            //超过最大值
            if(curValue > [self.paraModel.max integerValue])
            {
                curValue = [self.paraModel.max integerValue];
            }
            self.textField.text = [NSString stringWithFormat:@"%ld",curValue];
            
        }else{
            curValue = [self.paraModel.max integerValue];
            
        }
        self.textField.text = [NSString stringWithFormat:@"%ld",curValue];
        self.addBtn.userInteractionEnabled = curValue == [self.paraModel.max integerValue]?NO:YES;
        self.reduceBtn.userInteractionEnabled = curValue == [self.paraModel.min integerValue]?NO:YES;
        self.paraModel.content = [NSString stringWithFormat:@"%ld",curValue];
        //更新其他的位数据(只有int类型)
        if(self.paraModel.isBit&&self.bitValueChangBlock){
            self.bitValueChangBlock(self.paraModel);
        }
    }else if ([self.paraModel.format isEqualToString:@"float"]){
        
        NSDecimalNumber *curValue = [NSDecimalNumber decimalNumberWithString:self.paraModel.content];
        NSDecimalNumber *step = [NSDecimalNumber decimalNumberWithString:self.paraModel.unitLen];
        NSDecimalNumber *result;
        if(self.paraModel.content.length == 0){
            result = [NSDecimalNumber decimalNumberWithString:self.paraModel.min];
        }else{
            result = [curValue decimalNumberByAdding:step];
           
            //超过最大值
            if([curValue doubleValue] > [self.paraModel.max floatValue]){
                result = [NSDecimalNumber decimalNumberWithString:self.paraModel.max];
            }
        }
        
        self.textField.text = [NSString stringWithFormat:@"%@",result];
        self.paraModel.content = [NSString stringWithFormat:@"%@",result];
        self.addBtn.enabled = [result doubleValue] >= [self.paraModel.max doubleValue]?NO:YES;
        self.reduceBtn.enabled = [result doubleValue] <= [self.paraModel.min doubleValue]?NO:YES;
        
    }
}
//减
-(void)reduceAction
{
    if([self.paraModel.format isEqualToString:@"int"]){
        NSInteger curValue = [self.paraModel.content integerValue];
        NSInteger step = [self.paraModel.unitLen integerValue];
        if(curValue> [self.paraModel.min integerValue]){
            curValue -= step;
            //超出最小值
            if(curValue < [self.paraModel.min integerValue]){
                curValue = [self.paraModel.min integerValue];
            }
        }else{
            curValue = [self.paraModel.min integerValue];
            
        }
        self.paraModel.content = [NSString stringWithFormat:@"%ld",curValue];
        self.textField.text = [NSString stringWithFormat:@"%ld",curValue];
        self.reduceBtn.userInteractionEnabled = curValue == [self.paraModel.min integerValue]?NO:YES;
        self.addBtn.userInteractionEnabled = curValue == [self.paraModel.max integerValue]?NO:YES;
        //更新其他的位数据(只有int类型)
        if(self.paraModel.isBit&&self.bitValueChangBlock){
            self.bitValueChangBlock(self.paraModel);
        }
    }else if ([self.paraModel.format isEqualToString:@"float"]){
        NSDecimalNumber *curValue = [NSDecimalNumber decimalNumberWithString:self.paraModel.content];
        NSDecimalNumber *step = [NSDecimalNumber decimalNumberWithString:self.paraModel.unitLen];
        NSDecimalNumber *result;
        if(self.paraModel.content.length == 0){
            result = [NSDecimalNumber decimalNumberWithString:self.paraModel.min];
        }else{
            result = [curValue decimalNumberBySubtracting:step];
            //超出最小值
            if([result doubleValue] < [self.paraModel.min doubleValue]){
                result = [NSDecimalNumber decimalNumberWithString:self.paraModel.min];
            }
        }
        
        self.paraModel.content = [NSString stringWithFormat:@"%@",result];
        self.textField.text = [NSString stringWithFormat:@"%@",result];
        self.addBtn.enabled = [result doubleValue] >= [self.paraModel.max doubleValue]?NO:YES;
        self.reduceBtn.enabled = [result doubleValue] <= [self.paraModel.min doubleValue]?NO:YES;
        //更新其他的位数据
        if(self.paraModel.isBit&&self.bitValueChangBlock){
            self.bitValueChangBlock(self.paraModel);
        }
    }
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField.text.length==0) return;
    
    if([self.reuseIdentifier isEqualToString:LocalSettingAddSubCell]){
        self.paraModel.content = textField.text;
        if([self.paraModel.format isEqualToString:@"int"]){
            if([textField.text integerValue] > [self.paraModel.max integerValue]){
                self.textField.text = self.paraModel.max;
                self.paraModel.content = self.paraModel.max;
            }
            if([textField.text integerValue] < [self.paraModel.min integerValue]){
                self.textField.text = self.paraModel.min;
                self.paraModel.content = self.paraModel.min;
            }
            //更新其他的位数据(只有int类型)
            if(self.paraModel.isBit&&self.bitValueChangBlock){
                self.bitValueChangBlock(self.paraModel);
            }
        }
        
        if([self.paraModel.format isEqualToString:@"float"]){
            if([textField.text doubleValue] > [self.paraModel.max doubleValue]){
                self.textField.text = self.paraModel.max;
                self.paraModel.content = self.paraModel.max;
            }
            if([textField.text doubleValue] < [self.paraModel.min doubleValue]){
                self.textField.text = self.paraModel.min;
                self.paraModel.content = self.paraModel.min;
            }
        }
    }
    
}

#pragma mark -------- 加减项只能输入正负值
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([self.reuseIdentifier isEqualToString:LocalSettingAddSubCell]) {
        return  [NSString checkIsIntOrDecimalNumber:range textFieldContent:textField.text inputString:string];
    }
    
    return YES;
}
#pragma mark ---------- lazy load ---------

-(QMUILabel *)contentLab
{
    if (!_contentLab) {
        _contentLab = [[QMUILabel alloc]init];
        _contentLab.numberOfLines = 0;
        _contentLab.font = [UIFont systemFontOfSize:13];
        _contentLab.textAlignment = NSTextAlignmentCenter;
        _contentLab.textColor = kCOLOR_HEX(@"3F4443");
    }
    return _contentLab;
}
-(QMUITextField *)textField
{
    if(!_textField){
        _textField = [[QMUITextField alloc]init];
        _textField.textAlignment = NSTextAlignmentCenter;
        _textField.font = kSYSTEMFONT(13);
        _textField.textColor = kCOLOR_HEX(@"3F4443");
        _textField.layer.cornerRadius = 5;
        _textField.layer.borderColor = kCOLOR_HEX(@"DCDCDC").CGColor;
        _textField.layer.borderWidth = 1;
        _textField.layer.masksToBounds = YES;
        
    }
    return _textField;
}

-(QMUIButton *)addBtn
{
    if(!_addBtn){
        _addBtn = [[QMUIButton alloc]init];
        [_addBtn setTitle:@"+" forState:UIControlStateNormal];
        _addBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_addBtn setTitleColor:kCOLOR_HEX(@"3F4443") forState:UIControlStateNormal];
        _addBtn.layer.cornerRadius = 5;
        _addBtn.layer.borderColor = kCOLOR_HEX(@"DCDCDC").CGColor;
        _addBtn.layer.borderWidth = 1;
        _addBtn.layer.masksToBounds = YES;
        kWeakSelf;
        [[_addBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf addAction];
                
        }];
    }
    return _addBtn;
}

-(QMUIButton *)reduceBtn
{
    if(!_reduceBtn){
        _reduceBtn = [[QMUIButton alloc]init];
        [_reduceBtn setTitle:@"-" forState:UIControlStateNormal];
        _reduceBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_reduceBtn setTitleColor:kCOLOR_HEX(@"3F4443") forState:UIControlStateNormal];
        _reduceBtn.layer.cornerRadius = 5;
        _reduceBtn.layer.borderColor = kCOLOR_HEX(@"DCDCDC").CGColor;
        _reduceBtn.layer.borderWidth = 1;
        _reduceBtn.layer.masksToBounds = YES;
        kWeakSelf;
        [[_reduceBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf reduceAction];
        }];
    }
    return _reduceBtn;
}

-(QMUIButton *)selectBtn
{
    if(!_selectBtn){
        _selectBtn = [[QMUIButton alloc]init];
        
        kWeakSelf;
        
        [[_selectBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if([weakSelf.reuseIdentifier isEqualToString:LocalSettingSelectCell]){
                
                if(weakSelf.selectBlock){
                    weakSelf.selectBlock();
                }
            }
            if([self.reuseIdentifier isEqualToString:LocalSettingDateCell]){
                if(weakSelf.dateBlock){
                    weakSelf.dateBlock();
                }
            }
        }];
    }
    return _selectBtn;
}

@end
